package com.qq.utils;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;

/**
 * @author： Aeolia
 * @Description： TODO
 * @Date： 2021/10/16 15:48
 */
public class JDBCUtils {

    private static String driver;
    private static String url;
    private static String user;
    private static String password;

    static {
        URL resource = JDBCUtils.class.getClassLoader().getResource("JDBC.properties");
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream(resource.getPath()));
            driver = (String) properties.get("jdbc.driver");
            url = (String) properties.get("jdbc.url");
            user = (String) properties.get("jdbc.username");
            password = (String) properties.get("jdbc.password");

            Class.forName(driver);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        try {
            Connection connection = JDBCUtils.getConnection();
            PreparedStatement statement = (PreparedStatement) connection.createStatement();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }


    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, user, password);
    }


    public static void close(Connection connection, Statement statement, ResultSet resultSet) {
        if (null != resultSet) {
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                resultSet = null;
            }
        }
        close(connection, statement);
    }

    private static void close(Connection connection, Statement statement) {
        if (null != statement) {
            try {
                statement.close();
            } catch (SQLException throwables) {
                statement = null;
            }
        }
        if (null != connection) {
            try {
                connection.close();
            } catch (SQLException throwables) {
                connection = null;
            }
        }
    }


}
